package assignment;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2025-02-17
 * Time: 22:10
 */
//在子线程执行完毕后再执行主线程代码
//有20个线程，需要同时启动。
//每个线程按0-19的序号打印，如第一个线程需要打印0
//请设计代码，在main主线程中，等待所有子线程执行完后，再打印 ok

public class Demo2 {

    private static int current = 0;

    private static Object locker = new Object();

    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("1");
            }
        });
        t.start();
        System.out.println("2");
    }

    public static void main1(String[] args) throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            int flag = i;
            new Thread(() -> {
                printInorder(flag);
            }).start();
        }
        while (current < 20) {
            Thread.sleep(1000);
        }
        System.out.println("ok");
    }

    private static void printInorder(int target) {
        synchronized (locker) {
            while (current != target) {
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("线程 " + current + " 打印 " + current);
            current++;
            locker.notifyAll();
        }
    }
}
